package com.dhcc.cdc.busi.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.dhcc.cdc.busi.dao.*;
import com.dhcc.cdc.busi.entity.*;
import com.dhcc.cdc.busi.service.ICdcLocationService;
import com.dhcc.cdc.sys.dao.CdcDataMapper;
import com.dhcc.cdc.sys.entity.CdcDataEntity;
import com.dhcc.core.framework.base.service.impl.BaseServiceImpl;
import com.dhcc.core.framework.util.CommonUtil;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * 科室病区表数据服务层接口
 * 
 * @ClassName: CdcLocationServiceImpl
 * @Description: TODO
 * @author jumper
 * @date 2021-03-15 10:20:07
 */
@Service("cdcLocationService")
public class CdcLocationServiceImpl extends BaseServiceImpl<CdcLocationMapper, CdcLocationEntity> implements ICdcLocationService {
	@Autowired
    private CdcDictionaryMapper cdcDictionaryMapper;
	
	@Autowired
	private CdcDictypeMapper cdcDictypeMapper;
	
	@Autowired
    private CdcHospitalMapper cdcHospitalMapper;
	
	@Autowired
	private CdcUserMapper cdcUserMapper;
	
	@Autowired
	private CdcDataMapper cdcDataMapper;
	
	@Override
	public List<CdcLocationEntity> page(Page<CdcLocationEntity> page, Map<String, Object> map) {
		return this.baseMapper.page(page, map);
	}
	@Override
	public List<CdcLocationEntity> list(Map<String, Object> map) {
		return this.baseMapper.list(map);
	}

	@Override
	public JSONArray getDepartMap() {
		List<CdcLocationEntity> cdcLocationEntities = this.baseMapper.selectList(null);
		JSONArray officeArry = new JSONArray();
		JSONObject obj = new JSONObject();
		obj.put("value", "");
		obj.put("text","全部");
		officeArry.add(obj);
		for(CdcLocationEntity locationEntity : cdcLocationEntities){
			JSONObject officeObj = new JSONObject();
			officeObj.put("value", locationEntity.getId() + "");
			officeObj.put("text", locationEntity.getDescription());
			officeArry.add(officeObj);
		}
		return officeArry;
	}
	@Override
	public String handleXmlData(String dataStr) {

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		Document doc = null;
        try {
            doc = DocumentHelper.parseText(dataStr); // 将字符串转为XML
            Element rootElt = doc.getRootElement(); // 获取根节点
            Iterator<Element> iter = rootElt.elementIterator("location"); // 获取根节点下的子节点location
            // 遍历location节点
            while (iter.hasNext()) {
                Element locEle = iter.next();
                String xcode= locEle.elementTextTrim("xcode"); //唯一标识
                String code= locEle.elementTextTrim("code"); //代码	
                String description= locEle.elementTextTrim("description"); //描述
                String description2= locEle.elementTextTrim("description2"); //别名
                String busloctypecode= locEle.elementTextTrim("busloctypecode"); //类型
                String busloctypedesc= locEle.elementTextTrim("busloctypedesc"); //类型	
                String buslocrolecode= locEle.elementTextTrim("buslocrolecode"); //角色
                String buslocroledesc= locEle.elementTextTrim("buslocroledesc"); //角色	
                String isoperstr= locEle.elementTextTrim("isoper"); //是否手术科室
                String isnicustr= locEle.elementTextTrim("isnicu"); //是否新生儿病房
                String isicustr= locEle.elementTextTrim("isicu"); //是否ICU病房
                String buslocicucode= locEle.elementTextTrim("buslocicucode"); //ICU科室类型
                String buslocicudesc= locEle.elementTextTrim("buslocicudesc"); //ICU科室类型
                String parlocid= locEle.elementTextTrim("parlocid"); //父指针
                String hospitalid= locEle.elementTextTrim("hospitalid"); //所属院区
                String updatetimestr= locEle.elementTextTrim("updatetime"); //更新时间
                String updateuserid= locEle.elementTextTrim("updateuserid"); //更新人
                String opercode= locEle.elementTextTrim("opercode"); //操作码
                CdcLocationEntity loc = new CdcLocationEntity();
                loc.setXcode(xcode);
                //获取dataid
    			CdcDataEntity cdcDataEntityBase = new CdcDataEntity();
    			cdcDataEntityBase.setCode("HisBase");
    			cdcDataEntityBase.setIsActive(1);
    			cdcDataEntityBase = cdcDataMapper.selectOne(cdcDataEntityBase);
        		Long basedataId = cdcDataEntityBase.getId();
                if(CommonUtil.isNotEmpty(updatetimestr)) {
            		Date updatetime = sdf.parse(updatetimestr);
            		loc.setUpdateDate(updatetime);
            	}
            	//获取更新人
            	if(CommonUtil.isNotEmpty(updateuserid)) {
            		CdcUserEntity cdcUserEntity = new CdcUserEntity();
            		cdcUserEntity.setXcode(updateuserid);
            		cdcUserEntity.setDataId(basedataId);
            		cdcUserEntity.setIsActive(1);
            		cdcUserEntity = cdcUserMapper.selectOne(cdcUserEntity);
            		//判断人员存在不存在
            		Long updateuser = null;
            		if(CommonUtil.isEmpty(cdcUserEntity)) {//不存在  保存到用户表里面
            			cdcUserEntity = new CdcUserEntity();
            			cdcUserEntity.setXcode(updateuserid);
                		cdcUserEntity.setIsActive(1);
            			cdcUserEntity.setCode("newuser"+updateuserid);
            			cdcUserEntity.setName("newuser"+updateuserid);
                		cdcUserEntity.setDataId(basedataId);
                		//保存用户
                		cdcUserMapper.insert(cdcUserEntity);
                		updateuser = cdcUserEntity.getId();
            		}else {
            			updateuser = cdcUserEntity.getId();
            		}
            		loc.setUpdateBy(updateuser);
            	}
                if("1".equals(opercode)) {//保存/修改
                	if(CommonUtil.isNotEmpty(code)) {
                		loc.setCode(code);
                	}
                	if(CommonUtil.isNotEmpty(description)) {
                		loc.setDescription(description);
                	}
                	if(CommonUtil.isNotEmpty(description2)) {
                		loc.setDescription2(description2);
                	}
                	//获取loctypeId
                	if(CommonUtil.isNotEmpty(busloctypecode)) {
                		CdcDictypeEntity cdcDictypeEntity = new CdcDictypeEntity();
                    	cdcDictypeEntity.setCode("bus_loc_type");
                    	cdcDictypeEntity.setIsActive(1);
                    	cdcDictypeEntity = cdcDictypeMapper.selectOne(cdcDictypeEntity);
                		Long dicloctypeId = cdcDictypeEntity.getId();
                		//如果没有对应ID就要插入
                		CdcDictionaryEntity cdcDictionaryEntity = new CdcDictionaryEntity();
                		cdcDictionaryEntity.setDictypeId(dicloctypeId);
                		cdcDictionaryEntity.setCode(busloctypecode);
                		cdcDictionaryEntity.setIsActive(1);
                		cdcDictionaryEntity = cdcDictionaryMapper.selectOne(cdcDictionaryEntity);
                		//判断字典存在不存在
                		Long busloctypeid = null;
                		if(CommonUtil.isEmpty(cdcDictionaryEntity)) {//不存在  保存到字典表里面
                			cdcDictionaryEntity = new CdcDictionaryEntity();
                			cdcDictionaryEntity.setDictypeId(dicloctypeId);
                			cdcDictionaryEntity.setCode(busloctypecode);
                			cdcDictionaryEntity.setDescription(busloctypedesc);
                			cdcDictionaryEntity.setIsActive(1);
                    		//保存字典
                			cdcDictionaryMapper.insert(cdcDictionaryEntity);
                			busloctypeid = cdcDictionaryEntity.getId();
                		}else {
                			busloctypeid = cdcDictionaryEntity.getId();
                		}
                		loc.setBusLocTypeId(busloctypeid);
                	}//获取locroleId
                	if(CommonUtil.isNotEmpty(buslocrolecode)) {
                		CdcDictypeEntity cdcDictypeEntity = new CdcDictypeEntity();
                    	cdcDictypeEntity.setCode("bus_loc_role");
                    	cdcDictypeEntity.setIsActive(1);
                    	cdcDictypeEntity = cdcDictypeMapper.selectOne(cdcDictypeEntity);
                		Long diclocroleId = cdcDictypeEntity.getId();
                		//如果没有对应ID就要插入
                		CdcDictionaryEntity cdcDictionaryEntity = new CdcDictionaryEntity();
                		cdcDictionaryEntity.setDictypeId(diclocroleId);
                		cdcDictionaryEntity.setCode(buslocrolecode);
                		cdcDictionaryEntity.setIsActive(1);
                		cdcDictionaryEntity = cdcDictionaryMapper.selectOne(cdcDictionaryEntity);
                		//判断字典存在不存在
                		Long buslocroleid = null;
                		if(CommonUtil.isEmpty(cdcDictionaryEntity)) {//不存在  保存到字典表里面
                			cdcDictionaryEntity = new CdcDictionaryEntity();
                			cdcDictionaryEntity.setDictypeId(diclocroleId);
                			cdcDictionaryEntity.setCode(buslocrolecode);
                			cdcDictionaryEntity.setDescription(buslocroledesc);
                			cdcDictionaryEntity.setIsActive(1);
                    		//保存字典
                			cdcDictionaryMapper.insert(cdcDictionaryEntity);
                			buslocroleid = cdcDictionaryEntity.getId();
                		}else {
                			buslocroleid = cdcDictionaryEntity.getId();
                		}
                		loc.setBusLocRoleId(buslocroleid);
                	}//获取locicuId
                	if(CommonUtil.isNotEmpty(buslocicucode)) {
                		CdcDictypeEntity cdcDictypeEntity = new CdcDictypeEntity();
                    	cdcDictypeEntity.setCode("bus_loc_icu");
                    	cdcDictypeEntity.setIsActive(1);
                    	cdcDictypeEntity = cdcDictypeMapper.selectOne(cdcDictypeEntity);
                		Long diclocicuId = cdcDictypeEntity.getId();
                		//如果没有对应ID就要插入
                		CdcDictionaryEntity cdcDictionaryEntity = new CdcDictionaryEntity();
                		cdcDictionaryEntity.setDictypeId(diclocicuId);
                		cdcDictionaryEntity.setCode(buslocicucode);
                		cdcDictionaryEntity.setIsActive(1);
                		cdcDictionaryEntity = cdcDictionaryMapper.selectOne(cdcDictionaryEntity);
                		//判断字典存在不存在
                		Long buslocicuid = null;
                		if(CommonUtil.isEmpty(cdcDictionaryEntity)) {//不存在  保存到字典表里面
                			cdcDictionaryEntity = new CdcDictionaryEntity();
                			cdcDictionaryEntity.setDictypeId(diclocicuId);
                			cdcDictionaryEntity.setCode(buslocicucode);
                			cdcDictionaryEntity.setDescription(buslocicudesc);
                			cdcDictionaryEntity.setIsActive(1);
                    		//保存字典
                			cdcDictionaryMapper.insert(cdcDictionaryEntity);
                			buslocicuid = cdcDictionaryEntity.getId();
                		}else {
                			buslocicuid = cdcDictionaryEntity.getId();
                		}
                		loc.setBusLocIcuId(buslocicuid);
                	}
                	if(CommonUtil.isNotEmpty(isoperstr)) {
						Integer isoper = Integer.valueOf(isoperstr);
						loc.setIsOper(isoper);
					}
                	if(CommonUtil.isNotEmpty(isnicustr)) {
                		Integer isnicu = Integer.valueOf(isnicustr);
                		loc.setIsNicu(isnicu);
                	}
                	if(CommonUtil.isNotEmpty(isicustr)) {
                		Integer isicu = Integer.valueOf(isicustr);
                		loc.setIsIcu(isicu);
                	}
                	Long hospid = null;
                	if(CommonUtil.isNotEmpty(hospitalid)) {
                		CdcHospitalEntity cdcHospitalEntity = new CdcHospitalEntity();
            			cdcHospitalEntity.setXcode(hospitalid);
            			cdcHospitalEntity.setDataId(basedataId);
            			cdcHospitalEntity.setIsActive(1);
            			cdcHospitalEntity = cdcHospitalMapper.selectOne(cdcHospitalEntity);
            			if(CommonUtil.isEmpty(cdcHospitalEntity)) {//不存在  保存到院区表里面
            				cdcHospitalEntity = new CdcHospitalEntity();
            				cdcHospitalEntity.setXcode(hospitalid);
                			cdcHospitalEntity.setIsActive(1);
                			cdcHospitalEntity.setDataId(basedataId);
                			cdcHospitalEntity.setCode("newhosp"+hospitalid);
                			cdcHospitalEntity.setDescription("newhosp"+hospitalid);
                			cdcHospitalMapper.insert(cdcHospitalEntity);
                			hospid = cdcHospitalEntity.getId();
            			}else {
            				hospid = cdcHospitalEntity.getId();
            			}
            			loc.setHospitalId(hospid);
                	}
                	if(CommonUtil.isNotEmpty(parlocid)) {
                		Wrapper<CdcLocationEntity> wrappertmp =  new EntityWrapper<CdcLocationEntity>();
                		wrappertmp.eq("xcode", parlocid);
                		wrappertmp.eq("data_id", basedataId);
                		wrappertmp.eq("is_active", 1);
                		CdcLocationEntity cdcLocationEntity = this.selectOne(wrappertmp);
            			Long loclongid = null;
            			if(CommonUtil.isEmpty(cdcLocationEntity)) {//不存在  保存到科室表里面
            				cdcLocationEntity = new CdcLocationEntity();
            				cdcLocationEntity.setXcode(parlocid);
            				cdcLocationEntity.setIsActive(1);
            				cdcLocationEntity.setDataId(basedataId);
            				cdcLocationEntity.setCode("newloc"+parlocid);
            				cdcLocationEntity.setDescription("newloc"+parlocid);
            				cdcLocationEntity.setHospitalId(hospid);
                			this.insert(cdcLocationEntity);
                			loclongid = cdcLocationEntity.getId();
            			}else {
            				loclongid = cdcLocationEntity.getId();
            			}
            			loc.setParLocId(loclongid);
                	}
                	loc.setDataId(basedataId);
                	loc.setIsActive(1);
                }else {
                	loc.setIsActive(0);
                }
                //先判断是不是有该对象
                Wrapper<CdcLocationEntity> wrapper =  new EntityWrapper<CdcLocationEntity>();
                wrapper.eq("xcode", loc.getXcode());
                wrapper.eq("data_id", basedataId);
                int count = this.selectCount(wrapper);
                if(count>0) {
                	this.update(loc, wrapper);
                }else {
                	this.insert(loc);
                }
            }
        } catch (DocumentException e) {
            e.printStackTrace();
            return "<response><status>0</status><message>"+e.getMessage()+"</message></response>";
        } catch (Exception e) {
            e.printStackTrace();
            return "<response><status>0</status><message>"+e.getMessage()+"</message></response>";
        }
		return "<response><status>1</status><message>ok</message></response>";
	}

}